/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月30日
 */
package com.massyframework.beanskin.runtime.framework;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.ModuleRuntimeException;
import com.massyframework.beanskin.StartStopAbility;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.framework.FrameworkStartedEvent;
import com.massyframework.beanskin.framework.FrameworkStartingEvent;
import com.massyframework.beanskin.framework.FrameworkStoppedEvent;
import com.massyframework.beanskin.framework.FrameworkStoppingEvent;
import com.massyframework.beanskin.util.exceptioncollect.ExceptionCollectUtils;

/**
 * 执行启停的运行框架
 * @author huangkh
 *
 */
class ActionableFramework extends InitializingFramework {
	
	private Logger logger = LoggerFactory.getLogger(ActionableFramework.class);
	
	private boolean running = false;
	
	/**
	 * @param builder
	 */
	public ActionableFramework(Builder builder) {
		super(builder);
		
	}
	
	

	@Override
	public synchronized boolean isRunning() {
		return this.running;
	}



	@Override
	public synchronized void start() throws Exception {
		if (this.running) return;
		
		this.init();
				
		//发布开始启动事件
		FrameworkStartingEvent startingEvent =
				new FrameworkStartingEvent(this);
		this.applyEvent(startingEvent);
		
		ExecutorService taskExecutor = new ExceptionCollectExecutorService(Executors.newFixedThreadPool(4));			
		List<Assembly> assemblies = this.getModuleRepository()
				.getModules( assembly-> assembly.getId() != 0, Assembly.class);
		for (Assembly assembly: assemblies) {
			taskExecutor.execute(new StartTask(assembly));
		}
		
		taskExecutor.shutdown();
		try {
		  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
		} catch (InterruptedException e) {

		}
		
		try {
			this.getFragmentMonitor().start();
		}catch(Exception e) {
			
		}
						
		//发布启动结束事件
		FrameworkStartedEvent startedEvent =
				new FrameworkStartedEvent(this);
		this.applyEvent(startedEvent);
		
		this.running = true;
		
		ConsoleReporter reporter = new ConsoleReporter();
		reporter.printReport(this);
	}

	@Override
	public synchronized void stop()  throws Exception{
		if (!this.running) return;
		
		//发布开始停止事件
		FrameworkStoppingEvent stoppingEvent =
				new FrameworkStoppingEvent(this);
		this.applyEvent(stoppingEvent);
				
		try {
			this.getFragmentMonitor().stop();
		}catch(Exception e) {
			
		}
		
		ExecutorService taskExecutor = new ExceptionCollectExecutorService(Executors.newFixedThreadPool(4));	
		List<Assembly> assemblies = this.getModuleRepository()
				.getModules( assembly-> assembly.getId() != 0, Assembly.class);
		for (Assembly assembly: assemblies) {
			taskExecutor.execute(new StopTask(assembly));
		}
		
		taskExecutor.shutdown();
		try {
		  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
		} catch (InterruptedException e) {

		}
		
		
		//发布开始停止事件
		FrameworkStoppedEvent stoppedEvent =
				new FrameworkStoppedEvent(this);
		this.applyEvent(stoppedEvent);
		
		this.running = false;
	}
	
	
	
	/**
	 * 启动装配件
	 * @param assembly {@link Assembly}
	 * @throws Exception
	 */
	public void start(Assembly assembly) throws Exception {
		((StartStopAbility)assembly).start();
	}
	
	/**
	 * 停止装配件
	 * @param assembly {@link Assembly}
	 * @throws Exception
	 */
	public void stop(Assembly assembly) throws Exception {
		((StartStopAbility)assembly).stop();;
	}
	
	private class StartTask implements Runnable {
		
		private Assembly assembly;
		
		public StartTask(Assembly assembly) {
			this.assembly = assembly;
		}
		
		@Override
		public void run() {
			try {
				start(this.assembly);
			}catch(Exception e) {
				if (logger.isErrorEnabled()) {
					logger.error("装配件启动失败.", e);
				}
				
				ModuleRuntimeException newException =
						new ModuleRuntimeException(this.assembly, e);
				ExceptionCollectUtils.addException(newException);
			}
		}
		
	}
	
	private class StopTask implements Runnable {
		
		private Assembly assembly;
		
		public StopTask(Assembly assembly) {
			this.assembly = assembly;
		}
		
		@Override
		public void run() {
			try {
				start(this.assembly);
			}catch(Exception e) {
				if (logger.isErrorEnabled()) {
					logger.error("装配件停止失败.", e);
				}
				
				ModuleRuntimeException newException =
						new ModuleRuntimeException(this.assembly, e);
				ExceptionCollectUtils.addException(newException);
			}
		}
		
	}
	
}
